package cn.dogger.easyboot.nio.handler;

import cn.dogger.easyboot.common.exception.SocketException;
import cn.dogger.easyboot.log.annotation.Slf4j;
import cn.dogger.easyboot.log.utils.Log;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;

/**
 * @author dogger
 * 2022/11/21 13:51
 */
@Slf4j
public class SocketUtils {



    /**
     * 聊天信息处理方法
     */
    public static void socketRead(SocketChannel channel) {
        try {
            //内存缓冲区
            ByteBuffer allocate = ByteBuffer.allocate(6);
            //如果channel没有设置非阻塞，则会在这里阻塞
            int read = channel.read(allocate);
            //读到数据
            if (read > 0) {
                Log.info("数据接收：" + new String(allocate.array()));
            } else if (read == -1) {
                channel.close();
                Log.info(channel.hashCode() + "客户端断开连接");
            }
        } catch (IOException e) {
            throw new SocketException(e);
        }
    }

}
